﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;

using System.Text;
using System.Text.Encodings.Web;

using System.Text.Json.Serialization;

using WXWorkSvc.Common.Models;
using WXWorkSvc.Common.Services;

namespace WXWorkSvc.Third;

public static class WXWord3rdExtensions
{
    /// <summary>
    /// AddAuthentication
    /// AddControllers
    /// AddHttpClient
    /// AddHttpContextAccessor
    /// WXDbContext
    /// JsonTempDataSerializer
    /// WXWork3rdConfig
    /// WXWork3rd
    /// </summary>
    /// <param name="services"></param>
    /// <param name="wxDbConnectionString"></param>
    /// <returns></returns>
    public static IServiceCollection AddWXWork3rd<T>(this IServiceCollection services, string wxDbConnectionString, IConfiguration configuration) where T : struct, Enum
    {
        services.AddSingleton<IRole, RoleBase<T>>();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option =>
        {
            option.LoginPath = new PathString("/account/login");
            option.AccessDeniedPath = new PathString("/account/denied");
        }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true, //是否验证Issuer
                ValidIssuer = configuration["Jwt:Issuer"], //发行人Issuer
                ValidateAudience = true, //是否验证Audience
                ValidAudience = configuration["Jwt:Audience"], //订阅人Audience
                ValidateIssuerSigningKey = true, //是否验证SecurityKey
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"]!)), //SecurityKey
                ValidateLifetime = true, //是否验证失效时间

                ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值，解决服务器端时间不同步问题（秒）
                RequireExpirationTime = true,
            };
        });


        services.AddHttpClient().AddHttpContextAccessor();

        services.AddSqlServer<WXDbContext>(wxDbConnectionString, null, ii => ii.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
        services.AddSingleton<WXWork3rdConfig>();
        services.AddSingleton<WXWork3rd>();
        services.AddSingleton<JWTService>();


        return services;
    }

}
